package com.tq68.weixin.controller.discounts;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.QrcodeApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.tq68.weixin.common.AppConstantEnum;
import com.tq68.weixin.common.interf.IBaseController;
import com.tq68.weixin.model.Bbs;
import com.tq68.weixin.model.CoinsLog;
import com.tq68.weixin.model.Discounts;
import com.tq68.weixin.model.ForumPic;
import com.tq68.weixin.model.Seller;
import com.tq68.weixin.utils.Base64ForFile;
import com.tq68.weixin.utils.DateUtils;
import com.tq68.weixin.vo.SellerVO;
import com.tq68.weixin.vo.UserVO;

public class DiscountsController extends ApiController implements IBaseController{

	public void index() {
		String status = getPara("status");
		if(StringUtils.isBlank(status)){
			setAttr("status", "0");
		}else{
			keepPara("status");
		}
		Integer sellerid = getParaToInt("sellerid",0);//扫码带过来的商家id
		setAttr("sellerid",sellerid);
		render("index.html");
	}
	
	public void configs(){
		keepPara("status");
		render("configs.html");
	}
	
	//根据商家账号（字符串长度为1-64）生成商家永久型二维码图片
	public void createScancode(){
		SellerVO sellervo = getSessionAttr("sellervo");
		Seller seller = Seller.dao.findById(sellervo.getId());
		if(seller!=null){
			String ticket = "";
			if(StringUtils.isBlank(seller.getScanCode())){
				ApiResult result = QrcodeApi.createPermanent(seller.getSellerAccount());
				ticket = result.getStr("ticket");
				seller.setScanCode(ticket);
				seller.update();
			}else{
				ticket = seller.getScanCode();
			}
			//根据二维码ticket获取图片显示地址
			String picUrl = QrcodeApi.getShowQrcodeUrl(ticket);
			setAttr("picUrl", picUrl);
		}else{
			setAttr("picUrl", "ERROR");
		}
		render("scancode.html");
	}
	
	public void list() {
		UserVO uservo = getSessionAttr("uservo");
		Integer userid = uservo!=null?uservo.getUserid():0;
		SellerVO sellervo = getSessionAttr("sellervo");
		Integer sellerid = sellervo!=null?sellervo.getId():0;
		Integer status = getParaToInt("status",0);
		Integer currentPage = getParaToInt("currentPage",1);
		String path = getAttrForStr("imgPath");
		String contextPath = getRequest().getContextPath();
		Integer commuid = 0;
		if(uservo!=null){//用户视角
			commuid = uservo.getUserCommunityId();
		}else{
			commuid = sellervo.getCommuid();
		}
		Integer selleridFromScan = uservo!=null?uservo.getSelleridFromScan():0;
		setAttr("datalist", Bbs.dao.getDiscountsBbsList(currentPage, AppConstantEnum.PAGE_SIZE,userid,path,sellerid,status,selleridFromScan,commuid,contextPath));
		render("_list.html");
	}

	public void add() {
//		Calendar ca = Calendar.getInstance();
//		Date tdate = ca.getTime();
//		ca.add(Calendar.DAY_OF_MONTH, 1);
//		Date nextdate = ca.getTime();
//		setAttr("tdate",DateUtils.toDateStr(tdate));
//		setAttr("nextdate",DateUtils.toDateStr(nextdate));
		render("add.html");
	}
	
	@Before(Tx.class)
	public void addEntity() {
		SellerVO sellervo = getSessionAttr("sellervo");
		if(sellervo.getCoinsPerBbs() > sellervo.getCoins()){
			try {
				throw new Exception("金币不够");
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				redirect("/discounts");
			}
		}
		if(sellervo.getDeployedNum() >= AppConstantEnum.DISCOUNT_PER_DAY){
			try {
				throw new Exception("当天发帖数已用完。");
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				redirect("/discounts");
			}
		}
		String[] base64Imgs = getParaValues("base64Img");
		String comments = getPara("comments");
		Integer activeStart = getParaToInt("activeStart",2);
		Integer duration = getParaToInt("duration",1);
		String activeStartDate = getStartDate(activeStart);
		String activeEndDate = getEndDate(activeStart,duration);
		Integer bbsid = 0;
		Integer forumSubject = Integer.parseInt(AppConstantEnum.SubjectType.Discounts.getCode()); //优惠信息类主题
		Integer userid = sellervo.getId();
		String nickname = sellervo.getSellerName();
		Integer userlevel = sellervo.getLevelNum();
		Bbs bbs = new Bbs();
		Integer imgNum = base64Imgs.length;
		if(imgNum>2){//初始商家只能付2张图片
			imgNum = 2;
		}
		for(int i=0;i<imgNum;i++){
			ForumPic pic = new ForumPic();
			//对字节数组字符串进行Base64解码并生成图片
			String fileName = Base64ForFile.GenerateImage(base64Imgs[i]);
			if(i==0){
				bbs.setForumSubject(forumSubject);
				bbs.setContent(comments);
				bbs.setAddtime(DateUtils.toTimeStr(new Date()));
				bbs.setMainpicPath(fileName);
				bbs.setUserid(userid);
				bbs.setNickname(nickname);
				bbs.setUserlevel(userlevel);
				bbs.setCommuid(sellervo.getCommuid());
				bbs.setCommuName(sellervo.getCommuName());
				if(activeStart==1){
					bbs.setStatus(Integer.parseInt(AppConstantEnum.BbsStatus.Active.getCode()));
				}else{
					bbs.setStatus(Integer.parseInt(AppConstantEnum.BbsStatus.Waiting.getCode()));
				}
				//测试阶段，暂时只要发布就生效，后续要按规则来
				//bbs.setStatus(Integer.parseInt(AppConstantEnum.BbsStatus.Active.getCode()));
				bbs.save();
				bbsid = bbs.getId();
				Discounts dis = new Discounts();
				dis.setBbsid(bbsid);
				dis.setCostCoin(sellervo.getCoinsPerBbs());
				dis.setActiveDateStart(activeStartDate);
				dis.setActiveDateEnd(activeEndDate);
				dis.setDiscountDay(duration);
				dis.save();
				pic.setType(Integer.parseInt(AppConstantEnum.BbsPicType.Main.getCode()));
			}else{
				pic.setType(Integer.parseInt(AppConstantEnum.BbsPicType.Detail.getCode()));
			}
			pic.setBbsid(bbsid);
			pic.setFilename(fileName);
			pic.save();
		}
		//发帖成功减去金币
		Seller.dao.costCoinPerBbs(sellervo.getId(),sellervo.getCoins()-sellervo.getCoinsPerBbs());
		//金币减去成功，记录金币变更日志
		CoinsLog cl = new CoinsLog();
		cl.setUserid(sellervo.getId());
		cl.setAddtime(DateUtils.toTimeStr(new Date()));
		cl.setCoins(0-sellervo.getCoinsPerBbs());//存入负数
		cl.setTtype(1);// 0--用户表 1--商家表
		cl.setRemark("发布优惠\""+bbs.getContent().substring(0,3)+"...\"");
		cl.save();
		//更新已发布优惠数量
		sellervo.setDeployedNum(sellervo.getDeployedNum()+1);
		setSessionAttr("sellervo", sellervo);
		redirect("/discounts");
	}

	public void edit() {
		Bbs bbs = Bbs.dao.findById(getParaToInt("bbsid",0));
		setAttr("entity", bbs);
		render("edit.html");
	}

	public void editEntity() {
		
	}

	public void deleteEntity() {
		Bbs bbs = Bbs.dao.findById(getParaToInt("bbsid",0));
		if(bbs != null){
			bbs.delete();
			//删除图片
			//删除评论
			//删除点赞数
			//删除优惠信息扩展表
			
			//更新已发布优惠数量
			SellerVO sellervo = getSessionAttr("sellervo");
			sellervo.setDeployedNum(sellervo.getDeployedNum()-1);
			setSessionAttr("sellervo", sellervo);
		}
		redirect("/discounts");
	}
	
	public void downBbs() {
		Bbs bbs = Bbs.dao.findById(getParaToInt("bbsid",0));
		if(bbs != null){
			bbs.setStatus(Integer.parseInt(AppConstantEnum.BbsStatus.Inactive.getCode()));
			bbs.update();
		}
		redirect("/discounts");
	}
	
	public void extendBbs() throws ParseException{
		Integer days = getParaToInt("days",1);
		Discounts dis = Discounts.dao.findById(getParaToInt("disid",0));
		if(dis!=null){
			Calendar ca = Calendar.getInstance();
			ca.setTime(DateUtils.strToDate(dis.getActiveDateEnd()));
			ca.add(Calendar.DAY_OF_MONTH, days);
			dis.setActiveDateEnd(DateUtils.toDateStr(ca.getTime()));
			dis.update();
		}
		redirect("/discounts");
	}
	
	private String getStartDate(Integer activeStart){
		Calendar ca = Calendar.getInstance();
		String activeStartDate = DateUtils.toDateStr(ca.getTime());
		if(activeStart==2){//明天7点
			ca.add(Calendar.DAY_OF_MONTH, 1);
			activeStartDate = DateUtils.toDateStr(ca.getTime());
		}else if(activeStart==3){//后天7点
			ca.add(Calendar.DAY_OF_MONTH, 2);
			activeStartDate = DateUtils.toDateStr(ca.getTime());
		}
		return activeStartDate;
	}
	
	private String getEndDate(Integer activeStart, Integer duration){
		Calendar ca = Calendar.getInstance();
		String activeEndDate = "";
		if(activeStart==1){//立即
			ca.add(Calendar.DAY_OF_MONTH, (0+duration));
			activeEndDate = DateUtils.toDateStr(ca.getTime());
		}else if(activeStart==2){//明天7点
			ca.add(Calendar.DAY_OF_MONTH, (1+duration));
			activeEndDate = DateUtils.toDateStr(ca.getTime());
		}else if(activeStart==3){//后天7点
			ca.add(Calendar.DAY_OF_MONTH, (2+duration));
			activeEndDate = DateUtils.toDateStr(ca.getTime());
		}
		return activeEndDate;
	}
	
	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
}
